
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "write_shmem.h"
#include "mem_manage.h"
#include <unistd.h>
typedef unsigned char u_char;
typedef unsigned int u_int;
int m_semid;
void *m_smptr;
FILE *fp = NULL;

void * Create_mail_shmem(void)
{
    m_semid=getSem(S_SEM_NAME,S_SEM_ID,OPEN);
	mem_start=getMem(S_MEM_NAME,S_MEM_ID,TOTAL_LEN,OPEN);
	m_smptr=mem_start;
    return NULL;
}

int write_mail_shmem(mailinfo * mailhp,char * subject, char * text)
{
	u_char * mtext_mem = NULL;
	int sublen = 0;
	int textlen = 0;
	int totallen = 0;

	sublen  = strlen(subject)+1;
	textlen = strlen(text)+1;
	totallen= sublen + textlen;
	printf("totallen is %u\n",totallen);

	mtext_mem = (u_char*)malloc((4+totallen)*sizeof(char));
	assert(mtext_mem != NULL);
	memset(mtext_mem,0,4+totallen);
	memcpy(mtext_mem,&sublen,2);
	memcpy(mtext_mem+2,&textlen,2);
	memcpy(mtext_mem+4,subject,sublen);
    mtext_mem[4+sublen-1] = '\0';
	memcpy(mtext_mem+4+sublen,text,textlen);
	mtext_mem[4+sublen+textlen-1] = '\0';
    printf("mtext_mem is\n");
    printf("%s\n",mtext_mem+4);
    printf("%s\n",mtext_mem+4+sublen);
    //printf("%s\n",mtext_mem+8+sublen);
    //mtext_mem[4+totallen+1] = '\0';
	//begin to write to shmem
	while(fuckwrite(&m_smptr,mailhp,20,m_semid)!=0)
	{
		printf("write to mem wait1\n");
		sleep(1);
	}
	while(fuckwrite(&m_smptr,mtext_mem,(totallen+4),m_semid)!=0)
	{
		printf("write to mem wait2\n");
		sleep(1);
	}
	printf("write mem OK\n");
	free(mtext_mem);
	mtext_mem = NULL;
	printf("free tmp mem OK\n");
	return 0;
}
